﻿/* $RCSFile: CacheHelper.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/ADNCRM.Core/Helpers/CacheHelper.cs $
 * $log$
 * Revision 6 2010/08/06 19:56:28  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Web;
using System.Collections;
using System.Globalization;
using System.ServiceModel.Description;

using AddonNice.Design;
using AddonNice.Configuration;
using AddonNice.Configuration.Settings;
using AddonNice.Country;
using AddonNice.Diagnostics;
using AddonNice.Settings;
using AddonNice.Utilities;

using AddonNice.CRMWrapper;
using System.Net;


namespace AddonNice.Helpers
{
    public class CacheHelper
    {
        public static void Remove(string key,bool RemoveAll)
        {
            if ( CacheManagerTrace.Sw.TraceWarning )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CacheHelper Remove BEG key: {0}, RemoveAll: {1}.",key,RemoveAll),CacheManagerTrace.Sw.Info);

			if (HttpContext.Current == null)
                return;

            // Check flag in portal Settings
    		PortalSettings ps           =   (PortalSettings) HttpContext.Current.Items[StStr.strPortalSettings];
            if ( !ps.CustomSettings[StStr.SiteSettingsUseCacheManager].ToBool() )
                return;
                    
            try
            {
                Utilities.Utilities cacheUtil   =   new AddonNice.Utilities.Utilities();
                string url                      =    ps.CustomSettings[StStr.SiteSettingsPublicSiteUrl].ToString().Trim()+"/services/utilities.asmx";
                if ( CacheManagerTrace.Sw.TraceWarning )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CacheHelper Remove url: {0}, NetworkCredentials: '{1}'.",
                        url,(CredentialCache.DefaultNetworkCredentials == null ) ? string.Empty:CredentialCache.DefaultNetworkCredentials.UserName),CacheManagerTrace.Sw.Info);

                cacheUtil.Url                   =   url;
                cacheUtil.Credentials           =   CredentialCache.DefaultCredentials;
                cacheUtil.Remove(Config.CacheHandShake,key,RemoveAll);
            }
            catch ( Exception ex )
            {
                if ( CacheManagerTrace.Sw.TraceError )
                    Trace.WriteLine(string.Format(CultureInfo.InvariantCulture,"[E]CacheHelper Remove ex: {0}.",ex),CacheManagerTrace.Sw.Info);
            }
            if ( CacheManagerTrace.Sw.TraceWarning )
                Trace.WriteLine( "[V]CacheHelper Remove END.",CacheManagerTrace.Sw.Info);
        }

        public static DataTable MakeCacheTb(bool ShowDetail)
        {
            if ( CacheManagerTrace.Sw.TraceWarning )
                Trace.WriteLine( "[V]CacheHelper MakeCacheTb BEG.",CacheManagerTrace.Sw.Info);
            DataTable Tb                =   new DataTable("CacheTb");
            DataColumn c                =   Tb.Columns.Add("Key", typeof(string));
            Tb.Columns.Add("Area", typeof(string));
            Tb.Columns.Add("Type", typeof(string));
            Tb.Columns.Add("Size", typeof(int));
            Tb.Columns.Add("Value", typeof(string));
            Tb.PrimaryKey               =   new DataColumn[] { c };
            
            if ( CacheManagerTrace.Sw.TraceWarning )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CacheHelper MakeCacheTb Count: {0}.",HttpRuntime.Cache.Count),CacheManagerTrace.Sw.Info);
            foreach (DictionaryEntry cacheItem in HttpRuntime.Cache)
            {
                DataRow rw              =   Tb.NewRow();
                string key              =   (string)cacheItem.Key;
                //int keyLen              =   key.Length;
                rw["Key"]               =   key;
                Type ctp                =   cacheItem.Value.GetType();
                rw["Type"]              =   ctp.Name;
                rw["Area"]              =   "Global";

                if ( CacheManagerTrace.Sw.TraceWarning )
                    Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CacheHelper MakeCacheTb Type : {0}.",ctp.Name),CacheManagerTrace.Sw.Info);
                if ( key.IndexOf("CRM_CurrentOganization") != -1  )
                    rw["Area"]          =   "CRM";

                if ( cacheItem.Value is string )
                {
                    int len             =   ((string)cacheItem.Value).Length;
                    rw["Size"]          =   len;
                    rw["Value"]         =   (len> 200) ? ((string)cacheItem.Value).Substring(0,200):(string)cacheItem.Value;
                }
                else if ( cacheItem.Value is int )
                {
                    int len             =   2;
                    rw["Size"]          =   len;
                    rw["Value"]         =   cacheItem.Value.ToString();
                }
                else if ( cacheItem.Value is PageStripDetails )
                {
                    rw["Area"]          =   "Portal";
                    PageStripDetails pg =   cacheItem.Value as PageStripDetails;
                    rw["Size"]          =   1;
                    rw["Value"]         =   string.Format("ID: {0}, PageName: {1}, Flags: {2}, ParentPageID: {3}, PortalID: {4}, UrlName: {5}.",
                        new object[]{pg.PageID,pg.PageName,pg.Flags,pg.ParentPageID,pg.PortalID,pg.UrlName});
                }
                else if ( cacheItem.Value is ModulesLayout )
                {
                    rw["Area"]          =   "Portal";
                    ModulesLayout pg    =   cacheItem.Value as ModulesLayout;
                    rw["Size"]          =   1;
                    rw["Value"]         =   string.Format("ModulesLayout Name: {0}, FileName: {1}, ThemeParts: {2}.",
                                                        pg.Name,pg.ModulesLayoutFileName,pg.ThemeParts.Count);
                }
                else if ( cacheItem.Value is DataTable )
                {
                    rw["Area"]          =   "Portal";
                    DataTable pgs       =   cacheItem.Value as DataTable;
                    rw["Size"]          =   pgs.Rows.Count;
                    rw["Value"]         =   string.Format("{0} Columns: {1}",pgs.TableName,pgs.Columns.Count);
                }
                else if ( cacheItem.Value is Dictionary<string,string> )
                {
                    rw["Area"]          =   "Portal";
                    Dictionary<string,string> pgs       =   cacheItem.Value as Dictionary<string,string>;
                    rw["Size"]          =   pgs.Count;
                    StringBuilder sb    =   new StringBuilder();
                    if ( ShowDetail )
                        foreach ( string pg in pgs.Keys )
                        {
                            sb.AppendFormat("{0}: {1},<br />",pg,pgs[pg]);
                        }
                    else sb.AppendFormat("Count: {0}",pgs.Count);
                    rw["Value"]         =   sb.ToString();
                }
                else if ( cacheItem.Value is Hashtable )
                {
                    rw["Area"]          =   "Portal";
                    Hashtable pgs       =   cacheItem.Value as Hashtable;
                    rw["Size"]          =   pgs.Count;
                    StringBuilder sb    =   new StringBuilder();
                    if ( ShowDetail )
                        foreach ( DictionaryEntry pg in pgs )
                        {
                            sb.AppendFormat("{0}: {1},<br />",pg.Key,pg.Value);
                        }
                    else sb.AppendFormat("Count: {0}",pgs.Count);
                    rw["Value"]         =   sb.ToString();
                }
                else if ( cacheItem.Value is PageStripDetailsList )
                {
                    rw["Area"]          =   "Portal";
                    PageStripDetailsList pgs =   cacheItem.Value as PageStripDetailsList;
                    rw["Size"]          =   pgs.Count;
                    StringBuilder sb    =   new StringBuilder();
                    foreach ( PageStripDetails pg in pgs )
                    {
                        if ( ShowDetail )
                            sb.AppendFormat("ID: {0}, PageName: {1}, Flags: {2}, ParentPageID: {3}, PortalID: {4}, UrlName: {5},<br />",
                                new object[] { pg.PageID,pg.PageName,pg.Flags,pg.ParentPageID,pg.PortalID,pg.UrlName });
                        else sb.AppendFormat("{0}-{1}, ",pg.PageID,pg.PageName);
                    }
                    rw["Value"]         =   sb.ToString();
                }
                else if ( cacheItem.Value is string[] )
                {
                    rw["Area"]          =   "Portal";
                    string[] pgs   =   cacheItem.Value as string[];
                    rw["Size"]          =   pgs.Length;
                    StringBuilder sb    =   new StringBuilder();
                    foreach (string pg in pgs )
                    {
                        sb.AppendFormat("{0}, ",pg);
                    }
                    if ( sb.Length > 2 )
                        sb.Remove(sb.Length-3,2);
                    rw["Value"]         =   sb.ToString();
                }
                else if ( cacheItem.Value is CountryInfo[] )
                {
                    rw["Area"]          =   "Portal";
                    CountryInfo[] pgs   =   cacheItem.Value as CountryInfo[];
                    rw["Size"]          =   pgs.Length;
                    StringBuilder sb    =   new StringBuilder();
                    if ( ShowDetail )
                        foreach ( CountryInfo pg in pgs )
                        {
                                sb.AppendFormat("{0}: {1} - {2},<br />",pg.EnglishName,pg.CountryCode,pg.TwoLetterISOCountryName);
                        }
                    else sb.AppendFormat("Count: {0}.",pgs.Length);
                    rw["Value"]         =   sb.ToString();
                }
                else if ( cacheItem.Value is ArrayList )
                {
                    rw["Area"]          =   "Portal";
                    ArrayList pgs       =   cacheItem.Value as ArrayList;
                    rw["Size"]          =   pgs.Count;
                    StringBuilder sb    =   new StringBuilder();
                    foreach ( object pg in pgs )
                    {
                        if ( pg is string )
                            sb.AppendFormat("string: {0}, ",(string)pg);
                        else if ( pg is NameListItem) 
                            sb.AppendFormat("{0}, ",((NameListItem)pg).Name);
                        else if ( pg is ModulesLayoutItem) 
                            sb.AppendFormat("{0}, ",((ModulesLayoutItem)pg).Name);
                        else if ( pg is LayoutItem) 
                            sb.AppendFormat("{0}, ",((LayoutItem)pg).Name);
                        else if ( pg is MasterListItem) 
                            sb.AppendFormat("{0}-{1}, ",((MasterListItem)pg).Name,((MasterListItem)pg).WebPath);
                        else sb.AppendFormat("{0}, ",pg.ToString());
                    }
                    if ( sb.Length > 2 )
                        sb.Remove(sb.Length-3,2);
                    rw["Value"]         =   sb.ToString();
                }
                else if ( cacheItem.Value is PortalSettingsDictionary )
                {
                    rw["Area"]          =   "Portal";
                    PortalSettingsDictionary pgs       =   cacheItem.Value as PortalSettingsDictionary;
                    rw["Size"]          =   pgs.Count;
                    StringBuilder sb    =   new StringBuilder();
                    if ( ShowDetail )
                        foreach ( SettingItem pg in pgs.Values )
                        {
                            sb.AppendFormat("{0}: {1},<br />",pg.Key,pg.Value);
                        }
                    else sb.AppendFormat("Count: {0}, Created on {1}.",pgs.Count,pgs.ADNCreationDate.ToLocalTime());
                    rw["Value"]         =   sb.ToString();
                }
                else if ( cacheItem.Value is PageSettingsDictionary )
                {
                    rw["Area"]          =   "Portal";
                    PageSettingsDictionary pgs       =   cacheItem.Value as PageSettingsDictionary;
                    rw["Size"]          =   pgs.Count;
                    StringBuilder sb    =   new StringBuilder();
                    if ( ShowDetail )
                        foreach ( SettingItem pg in pgs.Values )
                        {
                            sb.AppendFormat("{0}: {1},<br />",pg.Key,pg.Value);
                        }
                    else sb.AppendFormat("Count: {0}, Created on {1}.",pgs.Count,pgs.ADNCreationDate.ToLocalTime());
                    rw["Value"]         =   sb.ToString();
                }
                else if ( cacheItem.Value is ModuleSettingsDictionary )
                {
                    rw["Area"]          =   "Portal";
                    ModuleSettingsDictionary pgs       =   cacheItem.Value as ModuleSettingsDictionary;
                    rw["Size"]          =   pgs.Count;
                    StringBuilder sb    =   new StringBuilder();
                    if ( ShowDetail )
                        foreach ( SettingItem pg in pgs.Values )
                        {
                            sb.AppendFormat("{0}: {1},<br />",pg.Key,pg.Value);
                        }
                    else sb.AppendFormat("Count: {0}, Created on {1}.",pgs.Count,pgs.ADNCreationDate.ToLocalTime());
                    rw["Value"]         =   sb.ToString();
                }
                else if ( cacheItem.Value is DynEntity )
                {
                    rw["Area"]          =   "CRM";
                    DynEntity ent       =   cacheItem.Value as DynEntity;
                    int len             =   ent.dicProperty.Count;
                    rw["Size"]          =   len;
                    StringBuilder sb    =   new StringBuilder();
                    sb.AppendFormat("EntityName: {0}, Created: {1}",ent.SchemaName, ent.ADNCreationDate.ToLocalTime());
                    if ( ent.HasPrimaryField )
                        sb.AppendFormat("<br />{0}: {1}, ",ent.PrimaryFieldName,ent.PrimaryFieldStringValue);
                    rw["Value"]         =   sb.ToString();
                    if ( CacheManagerTrace.Sw.TraceWarning )
                        Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CacheHelper MakeCacheTb DynEntity : {0}.",sb.ToString()),CacheManagerTrace.Sw.Info);
                }
                else if ( cacheItem.Value is SortedList<string,InternalAttributeMetadata> )
                {
                    rw["Area"]          =   "CRM";
                    SortedList<string,InternalAttributeMetadata> lst = cacheItem.Value as SortedList<string,InternalAttributeMetadata>;
                    int len             =   lst.Count;
                    rw["Size"]          =   len;
                    StringBuilder sb    =   new StringBuilder();
                    sb.AppendFormat("Count: {0}.",lst.Count);
                    rw["Value"]         =   sb.ToString();
                }

                else if ( cacheItem.Value is CRMFieldDescList )
                {
                    rw["Area"]          =   "CRM";
                    CRMFieldDescList ent=   cacheItem.Value as CRMFieldDescList;
                    rw["Size"]          =   ent.Count;
                    StringBuilder sb    =   new StringBuilder();
                    foreach (CRMLocFieldDesc pg in ent.Values )
                    {
                        sb.AppendFormat("{0}: {1},<br />",pg.FieldId,pg.Fieldname);
                    }
                    if ( sb.Length > 6 )
                        sb.Remove(sb.Length-7,6);
                    rw["Value"]         =   sb.ToString();
                }
                else if ( cacheItem.Value is InternalBusinessEntityArray )
                {
                    rw["Area"]          =   "CRM";
                    InternalBusinessEntityArray ent=   cacheItem.Value as InternalBusinessEntityArray;
                    StringBuilder sb    =   new StringBuilder();
                    int count           =0  ;
                    AddonNice.Security.PortalSecurity.Wrapper.Util.ExecForEachBusinessEntity(ent,delegate(InternalBusinessEntity bu)
                        {
                            if ( count == 0 )
                                sb.AppendFormat("Type: {0}.",bu.Content.GetType().Name);
                            count++;
                            return true;
                        });
                    rw["Size"]          =   count;
                    rw["Value"]         =   sb.ToString();
                }
                else if ( cacheItem.Value is object[] )
                {
                    rw["Area"]          =   "CRM";
                    object[] ent        =   cacheItem.Value as object[];
                    int len             =   ent.Length;
                    rw["Size"]          =   len;
                    StringBuilder sb    =   new StringBuilder();
                    for ( int i=0 ; i < ent.Length ; i++ )
                    {
                        if ( ent[i] is List<InternalRelationMetadata> )
                        {
                            List<InternalRelationMetadata> lst  =  ent[i] as List<InternalRelationMetadata>;
                            sb.AppendFormat("{0}-{1}, ",lst.Count, (lst.Count > 0) ? lst[0].Content.ToString():string.Empty);
                        }
                        else if ( ent[i] is ArrayList )
                        {
                            ArrayList lst  =  ent[i] as ArrayList;
                            sb.AppendFormat("{0}-{1}, ",lst.Count, (lst.Count > 0) ? lst[0].ToString():string.Empty);
                        }
                        else if ( ent[i] is string )
                            sb.AppendFormat("Timestamp: {0} ,",ent[i]);
                        else sb.AppendFormat("Type: {0} ,",ent[i]);
                    }
                    rw["Value"]         =   sb.ToString();
                }
                else 
                {
                    if ( ctp.IsArray )
                    {
                        int rk          =   ctp.GetArrayRank();
                        Type element    =   ctp.GetElementType();
                        if ( element == typeof(string) )
                        {
                            rw["Size"]  = ((string[])cacheItem.Value).Length;
                            rw["Value"] = ((string[])cacheItem.Value)[0];
                        }
                    }
                    else
                    {
                        string str      =   cacheItem.Value.ToString();
                        rw["Size"]      = -1;
                        rw["Value"]     = ( str.Length > 200 ) ? str.Substring(0,200) : str;
                    }
                }
 
                Tb.Rows.Add(rw);
            }
            if ( CacheManagerTrace.Sw.TraceWarning )
                Trace.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]CacheHelper MakeCacheTb END Rows.Count: {0}.",Tb.Rows.Count),CacheManagerTrace.Sw.Info);
            return Tb;
        }


    }
}
